package day02;

import exception.DataAccessException;
import util.JdbcUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@WebServlet("/modify")
public class ModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("ModifyEmpServlet.service()");

        Integer id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String salaryStr = request.getParameter("salary");
        Double salary = "".equals(salaryStr.trim())
                ? null
                : Double.parseDouble(salaryStr);
        String sex = request.getParameter("sex");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        String description = request.getParameter("description");


        System.out.println("name = " + name);
        System.out.println("salary = " + salary);
        System.out.println("sex = " + sex);
        System.out.println("edu = " + edu);
        System.out.println("Arrays.toString(hobbies) = " + Arrays.toString(hobbies));
        System.out.println("description = " + description);

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);


            String sql = new StringBuffer()
                    .append("update t_emp ")
                    .append("set name=?, ")
                    .append("    salary=?, ")
                    .append("    sex=?, ")
                    .append("    edu=?, ")
                    .append("    hobbies=?, ")
                    .append("    description=? ")
                    .append("where id=?")
                    .toString();

            ps = con.prepareStatement(sql);

            ps.setString(1, name);
            ps.setDouble(2, salary);
            ps.setString(3, sex);
            ps.setString(4, edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6, description);
            ps.setInt(7, id);

            ps.executeUpdate();

            con.commit();

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败", e);
        } finally {
            JdbcUtil.close(con, ps, rs);
        }


        response.sendRedirect(request.getContextPath() + "/list");
    }
}
